package com.evil.common.rocketmq.util;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.lang.Nullable;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * rocketMQ工具类
 *
 * @author liyang
 * @date 2025-03-07 11:08
 */
@Slf4j
@Component
@AllArgsConstructor
public class RocketMQUtil {

    private final RocketMQTemplate rocketMQTemplate;

    /**
     * 发送消息-信息头版本
     *
     * @param destination destination
     * @param payload     payload
     * @param headers     headers
     * @return SendResult
     */
    public SendResult syncSendWithHeaders(String destination, Object payload, @Nullable Map<String, Object> headers) {
        // 转换带请求头的消息
        Message<?> message = rocketMQTemplate.getMessageConverter().toMessage(payload, new MessageHeaders(headers));
        // 发送
        return rocketMQTemplate.syncSend(destination, message);
    }

    /**
     * 发送消息-信息头版本
     *
     * @param topic   topic
     * @param tag     tag
     * @param payload payload
     * @param headers headers
     * @return SendResult
     */
    public SendResult syncSendWithHeaders(String topic, String tag, Object payload, @Nullable Map<String, Object> headers) {
        return this.syncSendWithHeaders(RocketMQUtil.getDestination(topic, tag), payload, headers);
    }

    /**
     * 发送消息-普通版本
     *
     * @param destination destination
     * @param payload     payload
     * @return SendResult
     */
    public SendResult syncSendWithHeaders(String destination, Object payload) {
        // 发送
        return rocketMQTemplate.syncSend(destination, payload);
    }

    /**
     * 发送消息-普通版本
     *
     * @param topic   topic
     * @param tag     tag
     * @param payload payload
     * @return SendResult
     */
    public SendResult syncSendWithHeaders(String topic, String tag, Object payload) {
        return this.syncSendWithHeaders(RocketMQUtil.getDestination(topic, tag), payload);
    }

    /**
     * topic and tag
     *
     * @param topic topic
     * @param tag   tag
     * @return destination
     */
    public static String getDestination(String topic, String tag) {
        return String.format("%s:%s", topic, tag);
    }
}
